<?php
class GoodsService
{
	public function getGoodsNowList($where,$order = '',$fields = '',$limit = '',$args = array())
	{
		global $_FANWE;

		$result = array('list'=>array(),'ids'=>array());

		$limit = (empty($limit)) ? '' : ' LIMIT '.$limit;

		if(count($args) > 0 && !empty($args['is_auction']))
		{
			$acg_where = '';
			$auction_goods = array('ids'=>'','sorts'=>'');
			if(!empty($args['site_ids']))
			{
				if(count($args['site_ids']) == 1)
					$acg_where .= ' AND site_id = '.$args['site_ids'][0];
				else
					$acg_where .= ' AND '.DB::createIN($args['site_ids'],'site_id');
			}

			$res = DB::query('SELECT goods_id,MAX(auction_sort) as sort
						FROM '.DB::table('auction_city_goods').'
						WHERE status = 1 AND goods_id > 0 AND city_id = '.intval($_FANWE['current_city']['id']).$acg_where.' GROUP BY goods_id');

			while($acg = DB::fetch($res))
			{
				$auction_goods['ids'] .=','.$acg['goods_id'];
				$auction_goods['sorts'] .= ',\''.$acg['sort'].'\'';
			}

			if(!empty($auction_goods['ids']))
			{
				$auction_goods['ids'] = substr($auction_goods['ids'], 1);
				$auction_goods['sorts'] = substr($auction_goods['sorts'], 1);

				$fields.=",IF(FIND_IN_SET(g.id,'$auction_goods[ids]') > 0,MAKE_SET(POW(2,FIND_IN_SET(g.id,'$auction_goods[ids]')-1),$auction_goods[sorts]),0) as auction_sort";
			}
			else
				$fields.=",0 as auction_sort";
		}

		$group = ' GROUP BY g.id,gk.city';
		$query_where = 'WHERE 1 ';

		if(empty($where))
		{
			$query_where = '';
			$group = '';
		}
		else
			$query_where .= $where;

		$index = $this->getQueryIndex($where);

		if(count($args) > 0 && !empty($args['is_index']))
		{
			$index = $this->getQueryIndex($where.' AND gk.cate_id = 1');
			$page_count = intval($_FANWE['setting']['index_goods_count']);
			if($page_count == 0)
				$page_count = 9;

			foreach($_FANWE['cache']['goods']['root_cates'] as $cate_id)
			{
				$cids = array();
				$cate = $_FANWE['cache']['goods']['cats'][$cate_id];
				if(isset($cate['childs']))
					$cids = $cate['childs'];
				$cids[] = $cate_id;

				$cate_where = $query_where.' AND gk.cate_id IN ('.implode(',', $cids).')';

				$result['cates'][$cate_id]['list'] = array();
				$result['cates'][$cate_id]['gcount'] = 0;

				$res = DB::query('SELECT g.id,g.small_img,g.end_time,g.market_price,g.begin_time,g.shop_price,gk.city,gk.site_id,
							g.is_best,g.bought,g.name,g.sort,g.site_name,g.collect_buy,g.click_count,g.url,
							g.collect_count,g.add_time,(g.shop_price / g.market_price) AS discount'.$fields.'
							FROM '.DB::table('goods_now_key').' AS gk '.$index.'
							INNER JOIN '.DB::table('goods_now').' AS g ON g.id = gk.id
							'.$cate_where.$group.' ORDER BY '.$order.' LIMIT 0,'.$page_count);

				while($goods = DB::fetch($res))
				{
					$this->goodsFormat($goods);
					if($goods['auction_sort'] > 0)
					{
						$goods['url'] = U("goods/show",array("id"=>$goods['id'],'spread'=>$goods['auction_sort']));
						$goods['go_url'] = U("goods/go",array("id"=>$goods['id'],'spread'=>$goods['auction_sort']));
					}

					$result['cates'][$cate_id]['list'][] = $goods;
					$result['cates'][$cate_id]['gcount']++;
					$result['ids'][] = $goods['id'];
				}
			}
		}
		else
		{
			$area_query = '';

			if(strpos($where, 'ga.'))
			{
				$area_index = $this->getAreaIndex($where);
				$area_query = ' INNER JOIN '.DB::table('goods_area').' AS ga '.$area_index.' ON ga.goods_id = gk.id ';
			}

			$res = DB::query('SELECT g.id,g.small_img,g.end_time,g.market_price,g.begin_time,g.shop_price,gk.city,gk.site_id,
							g.is_best,g.bought,g.name,g.sort,g.site_name,g.collect_buy,g.click_count,g.url,
							g.collect_count,g.add_time,(g.shop_price / g.market_price) AS discount'.$fields.'
							FROM '.DB::table('goods_now_key').' AS gk '.$index.$area_query.'
							INNER JOIN '.DB::table('goods_now').' AS g ON g.id = gk.id
							'.$query_where.$group.' ORDER BY '.$order.$limit);

			while($goods = DB::fetch($res))
			{
				$this->goodsFormat($goods);
				if($goods['auction_sort'] > 0)
				{
					$goods['url'] = U("goods/show",array("id"=>$goods['id'],'spread'=>$goods['auction_sort']));
					$goods['go_url'] = U("goods/go",array("id"=>$goods['id'],'spread'=>$goods['auction_sort']));
				}

				$result['list'][] = $goods;
				$result['ids'][] = $goods['id'];
			}
		}

		return $result;
	}

	public function getGoodsNowCats($where)
	{
		global $_FANWE;

		$goods_index = $this->getQueryIndex($where.' AND gk.cate_id = gc.id');
		$area_query = '';

		if(strpos($where, 'ga.'))
		{
			$area_index = $this->getAreaIndex($where);
			$area_query = ' INNER JOIN '.DB::table('goods_area').' AS ga '.$area_index.' ON ga.goods_id = gk.id ';
		}

		$list = array();
		$list['gcount'] = 0;

		$res = DB::query('SELECT gc.id,gc.name,COUNT(DISTINCT gk.id) as gcount
						FROM '.DB::table('goods_cate').' AS gc
						INNER JOIN '.DB::table('goods_now_key').' AS gk'.$index.' ON gk.cate_id = gc.id
						'.$area_query.'INNER JOIN '.DB::table('goods_now').' AS g ON g.id = gk.id
						WHERE gc.status = 1 '.$where.' GROUP BY gc.id ORDER BY gc.sort ASC,gc.id ASC');

		while($cate = DB::fetch($res))
		{
			$list['gcount'] += $cate['gcount'];
			$list['cates'][$cate['id']] = $cate['gcount'];
		}

		foreach($_FANWE['cache']['goods']['root_cates'] as $root_id)
		{
			$root_cat = $_FANWE['cache']['goods']['cats'][$root_id];
			if(!isset($list['cates'][$root_id]))
				$list['cates'][$root_id] = 0;

			foreach($root_cat['childs'] as $child_id)
			{
				if(isset($list['cates'][$child_id]))
					$list['cates'][$root_id] += $list['cates'][$child_id];
				else
					$list['cates'][$child_id] = 0;
			}
		}

		return $list;
	}

	public function getGoodsNowArea($where)
	{
		global $_FANWE;

		if(empty($_FANWE['cache']['city_area_'.CURRENT_CITY_PY]))
			return false;

		$area_index = '';
		$goods_index = '';

		if(!empty($where))
		{
			$where = 'WHERE 1 '.$where;
			$area_index = $this->getAreaIndex($where);
			$goods_index = $this->getQueryIndex($where);
		}

		$list = array();
		$list['gcount'] = 0;

		$res = DB::query('SELECT ga.area,COUNT(DISTINCT gk.id) as gcount
						FROM '.DB::table('goods_area').' AS ga '.$area_index.$match_query.'
						INNER JOIN '.DB::table('goods_now_key').' AS gk'.$goods_index.' ON gk.id = ga.goods_id
						INNER JOIN '.DB::table('goods_now').' AS g ON g.id = gk.id '.$where.' GROUP BY ga.area');

		while($data = DB::fetch($res))
		{
			$list['areas'][$data['area']] = $data['gcount'];
		}

		foreach($_FANWE['cache']['city_area_'.CURRENT_CITY_PY]['roots'] as $root_id)
		{
			$root_area = $_FANWE['cache']['city_area_'.CURRENT_CITY_PY]['all'][$root_id];
			$root_name = $root_area['name'];
			if(!isset($list['areas'][$root_name]))
				$list['areas'][$root_name] = 0;
			else
				$list['gcount'] += $list['areas'][$root_name];

			foreach($root_area['childs'] as $child_id)
			{
				$child_name = $_FANWE['cache']['city_area_'.CURRENT_CITY_PY]['all'][$child_id]['name'];
				if(!isset($list['areas'][$child_name]))
					$list['areas'][$child_name] = 0;
			}
		}

		return $list;
	}

	public function getGoodsNowCount($where)
	{
		$query_where = 'WHERE 1';
		if(empty($where))
			$query_where = '';
		else
			$query_where.= $where;

		$index = $this->getQueryIndex($where);

		$area_query = '';

		if(strpos($where, 'ga.'))
		{
			$area_index = $this->getAreaIndex($where);
			$area_query = ' INNER JOIN '.DB::table('goods_area').' AS ga '.$area_index.' ON ga.goods_id = gk.id ';
		}

		return DB::resultFirst('SELECT COUNT(DISTINCT g.id)
			FROM '.DB::table('goods_now_key').' AS gk'.$index.$area_query.'
			INNER JOIN '.DB::table('goods_now').' AS g ON g.id = gk.id '.$query_where);
	}

	public function getExpiredGoodsList($where,$order = '',$fields = '',$limit = '')
	{
		$result = array('list'=>array(),'ids'=>array());

		$limit = (empty($limit)) ? '' : ' LIMIT '.$limit;

		$query_where = 'WHERE 1 ';

		if(empty($where))
			$query_where = '';
		else
			$query_where .= $where;

		$index = $this->getQueryIndex($where);

		$res = DB::query('SELECT g.id,g.small_img,g.end_time,g.market_price,g.begin_time,g.shop_price,g.city,g.site_id,
						g.is_best,g.bought,g.name,g.sort,g.site_name,g.collect_buy,g.click_count,g.url,
						g.collect_count,g.add_time,(g.shop_price / g.market_price) AS discount'.$fields.'
						FROM '.DB::table('goods_key').' AS gk '.$index.'
						INNER JOIN '.DB::table('goods').' AS g ON g.id = gk.id '
						.$query_where.' ORDER BY '.$order.$limit);

		while($goods = DB::fetch($res))
		{
			$this->goodsFormat($goods);
			$result['list'][] = $goods;
			$result['ids'][] = $goods['id'];
		}

		return $result;
	}

	public function getGoodsNowIdBySiteCity($site_id,$city)
	{
		global $_FANWE;

		$goods_id = 0;

		$where = " AND gk.city = '$city'";

		if($_FANWE['setting']['all_city'] == 1 && $city == '全国')
			$where = "";

		if($_FANWE['setting']['index_all'] == 1 && $city != '全国')
			$where = " AND gk.city IN ('$city','全国')";

		$goods = DB::fetchFirst("SELECT gk.id,(gk.city = '$city') AS is_current_city
				FROM ".DB::table('goods_now_key').' AS gk FORCE INDEX (site_city)
				WHERE gk.site_id = '.$site_id.$where.'
				ORDER BY is_current_city DESC,gk.id DESC LIMIT 0,1');

		if($goods)
			$goods_id = intval($goods['id']);

		return $goods_id;
	}

	public function getExpiredGoodsCount($where)
	{
		$query_where = 'WHERE 1';
		if(empty($where))
			$query_where = '';
		else
			$query_where.= $where;

		$index = $this->getQueryIndex($where);

		return DB::resultFirst('SELECT COUNT(DISTINCT g.id)
			FROM '.DB::table('goods_key').' AS gk'.$index.'
			INNER JOIN '.DB::table('goods').' AS g ON g.id = gk.id '.$query_where);
	}

	public function getExpiredGoodsDate($where)
	{
		$dates = DB::fetchFirst('SELECT MIN(end_time) AS min_time FROM '.DB::table('goods'));
		$dates['min_time'] = str2Time(toDate($dates['min_time'],'Y-m-d'));
		$dates['max_time'] = mktime(23,59,59,date('m'),date('d'),date('Y')) - date('Z');
		return $dates;
	}

	public function getQueryIndex($where)
	{
		$where = preg_replace("/'.*?'/i",'',$where);

		$force_index  = array();
		if(strpos($where, 'site_id'))
			$force_index[] = 'site';

		if(strpos($where, 'city'))
			$force_index[] = 'city';

		if(strpos($where, 'cate_id'))
			$force_index[] = 'cate';

		$index = implode('_',$force_index);

		if($index == 'site_cate')
			$index = 'site';

		if(!empty($index))
			$index = ' FORCE INDEX ('.$index.')';

		return $index;
	}

	public function getAreaIndex($where)
	{
		$where = preg_replace("/'.*?'/i",'',$where);

		$force_index  = array();

		if(strpos($where, 'ga.city'))
			$force_index[] = 'city';

		if(strpos($where, 'ga.area'))
			$force_index[] = 'area';

		$index = implode('_',$force_index);

		if(!empty($index))
			$index = ' FORCE INDEX ('.$index.')';

		return $index;
	}

	public function getTimes()
	{
		static $times = NULL;
		if($times === NULL)
		{
			$times['previous_month'] = mktime(00,00,00,toDate(TIME_UTC,'m') - 1,1,toDate(TIME_UTC,'Y')) - date('Z');
			$times['now_month'] = str2Time(toDate(TIME_UTC,'Y-m'));
		}

		return $times;
	}

	public function checkGoodsRangeExist()
	{
		global $_FANWE;
		static $position = NULL;

		$is_update = false;
		$cache_path = FANWE_ROOT.'./public/caches/table.cache.php';
		if(!@include $cache_path)
		{
			$is_partition = DB::fetchFirst("SHOW VARIABLES LIKE 'have_partitioning'");
			if($is_partition && strtolower($is_partition['Value']) == 'yes')
			{
				$position['is_partition'] = 1;
				$position = DB::fetchFirst('SELECT PARTITION_ORDINAL_POSITION,PARTITION_DESCRIPTION
												FROM INFORMATION_SCHEMA.PARTITIONS
												WHERE TABLE_NAME = \''.DB::table('goods_key').'\'
												AND TABLE_SCHEMA = \''.$_FANWE['config']['db'][1]['dbname'].'\'
												AND PARTITION_NAME IS NOT NULL
												ORDER BY PARTITION_DESCRIPTION DESC LIMIT 1,1');
                if(!$position)
                {
                    GoodsService::goodsRangeHandler();

                    $position = DB::fetchFirst('SELECT PARTITION_ORDINAL_POSITION,PARTITION_DESCRIPTION
												FROM INFORMATION_SCHEMA.PARTITIONS
												WHERE TABLE_NAME = \''.DB::table('goods_key').'\'
												AND TABLE_SCHEMA = \''.$_FANWE['config']['db'][1]['dbname'].'\'
												AND PARTITION_NAME IS NOT NULL
												ORDER BY PARTITION_DESCRIPTION DESC LIMIT 1,1');
                }

				$position['time'] = $position['PARTITION_DESCRIPTION'];
				$position['index'] = $position['PARTITION_ORDINAL_POSITION'];
				unset($position['PARTITION_DESCRIPTION']);
				unset($position['PARTITION_ORDINAL_POSITION']);
			}
			else
			{
				$position['is_partition'] = 0;
				$position['time'] = 0;
				$position['index'] = 0;
			}
			$is_update = true;
		}

		if($position['is_partition'] == 1)
		{
			$max_time = $position['time'];
			$max_index = $position['index'];

			if($max_time <= TIME_UTC)
			{
				$max_time = mktime(00,00,00,toDate(TIME_UTC,'m') + 1,1,toDate(TIME_UTC,'Y')) - date('Z');
				$max_index++;

				DB::query('ALTER TABLE '.DB::table('goods_key').' REORGANIZE PARTITION p'.($max_index).' INTO (
							PARTITION p'.($max_index).' VALUES LESS THAN ('.$max_time.'),
							PARTITION p'.($max_index + 1).' VALUES LESS THAN MAXVALUE)');

				$is_update = true;
			}
		}

		if($is_update == true)
		{
			$position['time'] = $max_time;
			$position['index'] = $max_index;

			$content = "<?php\r\n".'$position = '.var_export($position,true).";\r\n?>";
			writeFile($cache_path,$content);
		}
	}

    public function goodsRangeHandler()
    {
        $date = DB::resultFirst('SELECT MIN(end_time) FROM '.DB::table('goods_key'));
        $min_year = toDate($date,'Y');
        $min_month = toDate($date,'m');
        $max_year = toDate(TIME_UTC,'Y');
        $max_month = toDate(TIME_UTC,'m');
        $index = 1;

        $sql = 'ALTER TABLE '.DB::table('goods_key').' PARTITION BY RANGE(end_time)(';

        for($year = $min_year;$year <= $max_year;$year++)
        {
            $mmonth = 12;
            $month = 1;

            if($year == $max_year)
                $mmonth = $max_month;

            if($year == $min_year)
                $month = $min_month;

            for($month;$month <= $mmonth;$month++)
            {
                $next_year = $year;
                $next_month = $month + 1;

                if($month == 12)
                {
                    $next_year++;
                    $next_month = 1;
                }

                $time = str2Time($next_year.'-'.$next_month.'-01 00:00:00');
                $sql .= "PARTITION p$index VALUES LESS THAN ($time),";
                $index++;
            }
        }

        $sql .= "PARTITION p$index VALUES LESS THAN MAXVALUE)";
        DB::query($sql);
    }

	public function getExpiredGoodsCats($where)
	{
		global $_FANWE;

		$index = $this->getQueryIndex($where.' AND gk.cate_id = gc.id');

		$list = array();
		$list['gcount'] = 0;

		$res = DB::query('SELECT gc.id,gc.name,COUNT(gk.id) as gcount
						FROM '.DB::table('goods_cate').' AS gc
						INNER JOIN '.DB::table('goods_key').' AS gk'.$index.' ON gk.cate_id = gc.id
						INNER JOIN '.DB::table('goods').' AS g ON g.id = gk.id
						WHERE gc.status = 1 '.$where.' GROUP BY gc.id ORDER BY gc.sort ASC,gc.id ASC');

		while($cate = DB::fetch($res))
		{
			$list['gcount'] += $cate['gcount'];
			$list['cates'][$cate['id']] = $cate['gcount'];
		}

		foreach($_FANWE['cache']['goods']['root_cates'] as $root_id)
		{
			$root_cat = $_FANWE['cache']['goods']['cats'][$root_id];
			if(!isset($list['cates'][$root_id]))
				$list['cates'][$root_id] = 0;

			foreach($root_cat['childs'] as $child_id)
			{
				if(isset($list['cates'][$child_id]))
					$list['cates'][$root_id] += $list['cates'][$child_id];
				else
					$list['cates'][$child_id] = 0;
			}
		}

		return $list;
	}

	public function getExpiredGoodsSites($where)
	{
		$index = $this->getQueryIndex($where);

		$list = array();
		$res = DB::query('SELECT s.id,s.name,COUNT(gk.id) as gcount
						FROM '.DB::table('goods_key').' AS gk'.$index.'
						INNER JOIN '.DB::table('goods').' AS g ON g.id = gk.id
						INNER JOIN '.DB::table('site').' AS s ON s.id = gk.site_id
						WHERE s.status = 1 '.$where.' GROUP BY s.id ORDER BY s.sort ASC,s.id ASC');

		while($site = DB::fetch($res))
		{
			$list[] = $site;
		}

		return $list;
	}

	public function getGoodsClickRank($num)
	{
        global $_FANWE;

		$list = array();

        $add_num = abs(floatval($_FANWE['setting']['goods_click_add_num']));
        $add_count = -1;

        $rand = abs(intval($_FANWE['setting']['goods_click_add_rand']));
        $rand_count = 0;
        if($rand > 0)
            $rand_count =  mt_rand(0,$rand);

		$res = DB::query('SELECT g.id,g.site_id,g.click_count AS rank_count,g.name,g.site_name,g.add_time
						FROM '.DB::table('rank_statistic').' AS rs
						INNER JOIN '.DB::table('goods_now').' AS g ON g.id = rs.goods_id
						WHERE rs.type=\'SITE_MAX_GOODS_CLICK\' ORDER BY rs.nnum DESC,g.sort ASC,g.id DESC LIMIT 0,'.$num);

		while($data = DB::fetch($res))
		{
            if($add_count == -1)
            {
                $add_count = 0 + $rand_count;
                if($add_num > 0)
                    $add_count += ceil($add_num * (TIME_UTC - $data['add_time']) / 3600);
            }

            $data['rank_count'] += $add_count;
			$data['url'] = U("goods/show",array("id"=>$data['id']));
			$data['site_url'] = U("site/show",array("id"=>$data['site_id']));
			$list[] = $data;
		}

		return $list;
	}

	public function getGoodsBoughtRank($num)
	{
		$list = array();
		$res = DB::query('SELECT g.id,g.site_id,g.bought AS rank_count,g.name,g.site_name
						FROM '.DB::table('rank_statistic').' AS rs
						INNER JOIN '.DB::table('goods_now').' AS g ON g.id = rs.goods_id
						WHERE rs.type=\'SITE_MAX_GOODS_BOUGHT\' ORDER BY rs.nnum DESC,g.sort ASC,g.id DESC LIMIT 0,'.$num);

		while($data = DB::fetch($res))
		{
			$data['url'] = U("goods/show",array("id"=>$data['id']));
			$data['site_url'] = U("site/show",array("id"=>$data['site_id']));
			$list[] = $data;
		}

		return $list;
	}

	public function getGoodsBests($num)
	{
		$list = array();
		$res = DB::query('SELECT g.id,g.site_id,g.name,g.site_name,g.small_img
						FROM '.DB::table('goods_now').' AS g
						WHERE g.is_best = 1
						ORDER BY g.sort ASC,g.id DESC LIMIT 0,'.$num);

		while($data = DB::fetch($res))
		{
			if(!parseUrl($data['small_img']))
	 			$data['small_img'] = SITE_PATH.$data['small_img'];

			$data['url'] = U("goods/show",array("id"=>$data['id']));
			$data['site_url'] = U("site/show",array("id"=>$data['site_id']));
			$list[] = $data;
		}

		return $list;
	}

	public function getGoodsById($gid)
	{
		$goods = DB::fetchFirst('SELECT * FROM '.DB::table('goods').' WHERE id = '.$gid.' AND status = 1');
		if($goods)
			$this->goodsFormat($goods);
		else
			$goods = false;

		return $goods;
	}

	/*2011-02-28*/
	public function goodsFormat(&$goods)
	{
		global $_FANWE;
		static $today_time = NULL;
		if($today_time === NULL)
			$today_time= getTodayTime();

		if(!parseUrl($goods['small_img']))
	 		$goods['small_img'] = SITE_PATH.$goods['small_img'];

		if(!parseUrl($goods['big_img']))
	 		$goods['big_img'] = SITE_PATH.$goods['big_img'];

		$goods['end_time_old']  = $goods['end_time'];

		if($goods['end_time'] > TIME_UTC)
			$goods['end_time_lag']  = getEndTimelag($goods['end_time']);
		else
			$goods['end_time_lag']  = '';

		$goods['end_time_format']  = toDate($goods['end_time']);
		$goods['end_time']  = toDate($goods['end_time'],'r');
		$goods['market_price_format'] = "¥".floatval($goods['market_price']);
		$goods['shop_price_format'] = "¥".floatval($goods['shop_price']);
		$goods['discount'] = round(floatval($goods['discount']) * 10,2);
		if($goods['discount'] < 0)
			$goods['discount'] = 0;

		if(isset($goods['click_count']))
		{
			$rand = abs(intval($_FANWE['setting']['goods_click_add_rand']));
			$add_num = abs(floatval($_FANWE['setting']['goods_click_add_num']));
			if($add_num > 0)
				$goods['click_count'] += ceil($add_num * (gmtTime() - $goods['add_time']) / 3600);

			if($rand > 0)
				$goods['click_count'] += mt_rand(0,$rand);
		}

		$goods['save_format'] = "¥".(floatval($goods['market_price']) - floatval($goods['shop_price']));
		$goods['is_new']  = 0;

		if($goods['begin_time'] > $today_time)
			$goods['is_new']  = 1;

		$goods['url'] = U("goods/show",array("id"=>$goods['id']));
		$goods['go_url'] = U("goods/go",array("id"=>$goods['id']));
		$goods['site_url'] = U("site/show",array("id"=>$goods['site_id']));
	}

	/*2011-02-28*/
	public function runCron($crons = '')
	{
		global $_FANWE;

		set_time_limit(3600);
		if(function_exists('ini_set'))
			ini_set('max_execution_time',3600);

		DB::query('REPLACE INTO '.DB::table('cron_site').' SELECT site_id FROM '.DB::table('goods_now_key').' WHERE end_time <= '.TIME_UTC.' GROUP BY site_id');
		DB::query('DELETE FROM '.DB::table('goods_now')." WHERE end_time <= '".TIME_UTC."'");
		DB::query('DELETE FROM '.DB::table('goods_now_key')." WHERE end_time <= '".TIME_UTC."'");
		DB::query('DELETE FROM '.DB::table('goods_area')." WHERE end_time <= '".TIME_UTC."'");
		DB::query('DELETE FROM '.DB::table('suppliers')." WHERE end_time <= '".TIME_UTC."'");

		$count = intval(DB::resultFirst('SELECT COUNT(id) FROM '.DB::table('cron_site')));
		if($count > 0)
		{
			@file_put_contents(FANWE_ROOT.'./public/cron.lock','cron');
			@chmod(FANWE_ROOT.'./public/cron.lock', 0777);
			$this->clearGoodsCache();
		}
		else
		{
            @unlink(FANWE_ROOT.'./public/cron.lock');
		}
	}

	public function updateAuctionRank()
	{
		global $_FANWE;
		$res = DB::query("SELECT * FROM ".DB::table('auction_result')." WHERE auction_type = 1");
		while($result = DB::fetch($res))
		{
			usleep(10);
			$auction = S('auction')->getItem($result['auction_id']);
			if($auction)
			{
				if(count($auction['citys']) > 0 && $auction['citys'][0]['city_id'] > 0)
				{
					foreach($auction['citys'] as $city)
					{
						$goods_id = intval(DB::resultFirst('SELECT gn.id FROM '.DB::table('auction_city_goods').' AS acg FORCE INDEX (site_city)
															LEFT JOIN '.DB::table('goods_now').' AS gn ON gn.id = acg.goods_id
															WHERE acg.auction_id = '.$auction['id'].' AND acg.site_id = '.$result['rec_id'].' AND acg.city_id = '.$city['city_id']));
						if($goods_id == 0)
							$goods_id = S('goods')->getGoodsNowIdBySiteCity($result['rec_id'],$city['name']);

						$data = array(
							'auction_id'=>$auction['id'],
							'site_id'=>$result['rec_id'],
							'city_id'=>$city['city_id'],
							'goods_id'=>$goods_id,
							'auction_sort'=>$result['rec_data']
						);

						DB::insert('auction_city_goods',$data,false,true);
					}
				}
				else
				{
					foreach($_FANWE['cache']['city']['all'] as $city)
					{

						$goods_id = intval(DB::resultFirst('SELECT gn.id FROM '.DB::table('auction_city_goods').' AS acg
															LEFT JOIN '.DB::table('goods_now').' AS gn ON gn.id = acg.goods_id
															WHERE acg.auction_id = '.$auction['id'].' AND acg.site_id = '.$result['rec_id'].' AND acg.city_id = '.$city['id']));
						if($goods_id == 0)
							$goods_id = S('goods')->getGoodsNowIdBySiteCity($result['rec_id'],$city['name']);

						$data = array(
							'auction_id'=>$auction['id'],
							'site_id'=>$result['rec_id'],
							'city_id'=>$city['id'],
							'goods_id'=>$goods_id,
							'auction_sort'=>$result['rec_data']
						);

						DB::insert('auction_city_goods',$data,false,true);
					}
				}
			}
		}

		$res = DB::query("SELECT id FROM ".DB::table('site')." WHERE status = 1 ORDER BY sort ASC,id ASC");
		$fields = array('SITE_MAX_GOODS_CLICK'=>'click_count','SITE_MAX_GOODS_BOUGHT'=>'bought');

		while($site = DB::fetch($res))
		{
			$ids = '';
			$ids_res = DB::query('SELECT id FROM '.DB::table('goods_now_key').' FORCE INDEX (site) WHERE site_id = '.$site['id']);
			while($gid = DB::fetch($ids_res))
			{
				$ids .= ','.$gid['id'];
			}

			if(!empty($ids))
				$ids = substr($ids,1);

			foreach($fields as $key => $field)
			{
				if(empty($ids))
				{
					DB::query('DELETE FROM '.DB::table('rank_statistic')." WHERE site_id = '$site[id]' AND type = '$key'");
				}
				else
				{
					usleep(10);
					$max_goods = DB::fetchFirst("SELECT id,$field FROM ".DB::table('goods_now')."
											WHERE id in ($ids) ORDER BY $field DESC,sort ASC,id DESC LIMIT 0,1");
					if($max_goods)
					{
						$statistic = DB::fetchFirst('SELECT * FROM '.DB::table('rank_statistic')."
													WHERE site_id = '$site[id]' AND type = '$key'");

						$statistic['site_id'] = $site['id'];
						$statistic['goods_id'] = $max_goods['id'];
						$statistic['nnum'] = $max_goods[$field];
						$statistic['type'] = $key;
						$statistic['statistic_time'] = TIME_UTC;
						DB::insert('rank_statistic',$statistic,false,true);
					}
				}
			}
		}

		require_once import('function/cache');
		updateCache('goods');
		$this->clearGoodsCache();
	}

	public function clearGoodsCache()
	{
		clearDir(FANWE_ROOT.'./public/tpl/caches');
	}
}
?>